package com.tencent.qf.common.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tencent.qf.common.aspect.annotation.ApiLog;
import com.tencent.qf.common.config.SignatureConfig;
import com.tencent.qf.common.exception.ErrorCode;
import com.tencent.qf.common.pojo.HttpResult;
import com.tencent.qf.common.util.SignatureUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class ApiLogAspect {

    @Around("@annotation(apiLog)")
    public Object around(ProceedingJoinPoint joinPoint, ApiLog apiLog) throws Throwable {
        String logPrefix = apiLog.value();
        Object body = this.buildRequestBody(joinPoint);
        log.info(logPrefix + " 入参：{}", JSON.toJSONString(body));
        Object result = joinPoint.proceed();
        log.info(logPrefix + " 出参：{}", JSON.toJSONString(result));
        return result;
    }

    private Object buildRequestBody(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Object requestBody = new Object();
        if(args != null && args.length > 0){
            for(Object arg : args){
                if(arg instanceof HttpServletRequest){
                    continue;
                }
                if(arg instanceof HttpServletResponse){
                    continue;
                }
                if(arg instanceof MultipartFile){
                    continue;
                }
                requestBody = arg;
            }
        }
        return requestBody;
    }
}
